﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;

namespace Wyn.PMS.Entity.Construction
{
    public static class DataReaderExtensions
    {
        public static List<T> MapToList<T>(this DbDataReader dr) where T : new()
        {
            if (dr != null && dr.HasRows)
            {
                var entity = typeof(T);

                var entites = new List<T>();

                var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                var propDict = props.ToDictionary(p => p.Name.ToUpper(), p => p);

                while (dr.Read())
                {
                    T newObject = new T();

                    for (int index = 0; index < dr.FieldCount; index++)
                    {
                        if (propDict.ContainsKey(dr.GetName(index).ToUpper()))
                        {
                            var info = propDict[dr.GetName(index).ToUpper()];

                            var val = dr.GetValue(index);

                            info.SetValue(newObject, (val == DBNull.Value) ? null : val, null);
                        }
                    }
                    entites.Add(newObject);
                }
                return entites;
            }
            return null;
        }
    }
}
